package com.ckx.blog.Job;

import com.ckx.annotation.SysLog;
import com.ckx.constants.SystemConstants;
import com.ckx.domain.entity.Article;
import com.ckx.service.ArticleService;
import com.ckx.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 定时将 Redis的 浏览量更新到数据库
 */
@Component
public class UpdateViewCountJob {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private RedisCache redisCache;

    @Scheduled(cron = "0 0/10 * * * ?")
//    @Scheduled(cron = "0/2 * * * * ?")
    @SysLog(businessName = "定时更新任务")
    public void updateViewCountJob() {
        Map<String, Object> articleCountMap = redisCache.getCacheMap(SystemConstants.ARTICLE_VIEWCOUNT);
        Set<String> keySet = articleCountMap.keySet();
        List<Article> articles = keySet.stream()
                .map(key -> {
                    Integer viewCount = (Integer) articleCountMap.get(key);
                    return new Article(Long.parseLong(key), viewCount.longValue());
                }).collect(Collectors.toList());
        //批存入 rewriteBatchedStatements=true 提高 MYSQL批处理速度
        articleService.updateBatchById(articles);
    }

}
